import os
import time
import threading
from bottle import route, view
from mamba.tv import timer, next_timer_start
import mamba.config as config

WAKEALARM = "/sys/class/rtc/rtc0/wakealarm"
SHUTDOWN_CMD = config.config().get("system", "shutdown_command", fallback="sudo echo 0 > {wakealarm}; sudo echo {{wakeup}} > {wakealarm}; sudo shutdown -h now".format(wakealarm = WAKEALARM))

@route("/shutdown")
@view("message")
def _shutdown():
	print("ok")
	if can_shutdown() and False:
		shutdown(next_timer_start())
	else:
		threading.Thread(target=shutdown_wait)
		return dict(message="Shutdown will be performed after current TV recordings are finished.")

def shutdown_wait():
	while True:
		if can_shutdown():
			shutdown()
		else:
			time.sleep(60)

def can_shutdown():
	try:
		t = timer()
	except:
		return True
	for entry, running in t:
		if running:
			return False
		if entry["start"] - time.time() < 3600 and entry["end"] > time.time():
			return False
	return True

def shutdown(wakeup):
	os.system(SHUTDOWN_CMD.format(wakeup=wakeup))
